package com.liu.webstore.controller;

import com.liu.webstore.common.Constant;
import com.liu.webstore.entity.*;
import com.liu.webstore.enums.StatusEnum;
import com.liu.webstore.event.EventProducer;
import com.liu.webstore.service.*;
import com.liu.webstore.util.HostHolder;
import com.liu.webstore.util.WebstoreUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Author LiuYumei
 * @Date 2022/7/24 21:18
 */
@Controller
@RequestMapping("/discuss")
public class DiscussPostController {
    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private UserService userService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private ElasticsearchService elasticsearchService;

    @Autowired
    private EventProducer eventProducer;

    @PostMapping("/add")
    @ResponseBody
    public String addDiscussPost(String title, String content) {
        User user = hostHolder.getUser();
        if (Objects.isNull(user)) {
            return WebstoreUtil.getJsonString(403, "您还没有登录哦！");
        }
        DiscussPost discussPost = new DiscussPost();
        discussPost.setUserId(user.getId());
        discussPost.setTitle(title);
        discussPost.setContent(content);
        discussPost.setCreateTime(new Date());
        int row = discussPostService.addDiscussPost(discussPost);
        if (row < 1) {
            return WebstoreUtil.getJsonString(500, "发生错误，请联系管理员！");
        }
        // 触发发帖事件
        Event event = new Event()
                .setTopic(Constant.TOPIC_PUBLISH)
                .setUserId(user.getId())
                .setEntityType(StatusEnum.ENTITY_TYPE_POST.getStatus())
                .setEntityId(discussPost.getId());
        eventProducer.fireEvent(event);
        return WebstoreUtil.getJsonString(200, "发送成功！");
    }

    @GetMapping("/detail/{postId}")
    public String getDiscussPost(@PathVariable("postId") int postId, Model model, Page page) {
        int userId = hostHolder.getUser().getId();
        // 查询帖子
        DiscussPost discussPost = discussPostService.findDiscussPost(postId);
        model.addAttribute("post", discussPost);
        // 帖子点赞数
        Long discussLikeCount = likeService.findEntityLikeCount(StatusEnum.ENTITY_TYPE_POST.getStatus(), discussPost.getId());
        model.addAttribute("discussLikeCount", discussLikeCount);
        // 当前用户查看帖子的点赞状态
        Integer discussLikeStatus = likeService.findEntityLikeStatus(userId, StatusEnum.ENTITY_TYPE_POST.getStatus(), discussPost.getId());
        model.addAttribute("discussLikeStatus", discussLikeStatus);
        // 查询作者信息
        User user = userService.getUserById(discussPost.getUserId());
        model.addAttribute("user", user);
        // 查询评论分页信息
        page.setLimit(5);
        page.setPath("/discuss/detail/" + postId);
        page.setRows(discussPost.getCommentCount());
        // 评论：给帖子的评论
        // 回复：给评论的评论
        // 评论列表
        List<Comment> commentList = commentService.findCommentsByEntity(
                StatusEnum.ENTITY_TYPE_POST.getStatus(), discussPost.getId(), page.getOffert(), page.getLimit());
        List<Map<String, Object>> commentVoList = new ArrayList<>();
        if (Objects.nonNull(commentList)) {
            for (Comment comment : commentList) {
                // 评论vo列表
                Map<String, Object> commentVo = new HashMap<>();
                // 评论
                commentVo.put("comment", comment);
                // 作者
                commentVo.put("user", userService.getUserById(comment.getUserId()));
                // 帖子评论的点赞数
                Long commentLikeCount = likeService.findEntityLikeCount(StatusEnum.ENTITY_TYPE_POST.getStatus(), comment.getId());
                commentVo.put("commentLikeCount", commentLikeCount);
                // 当前用户查看帖子评论的点赞状态
                Integer commentLikeStatus = likeService.findEntityLikeStatus(userId, StatusEnum.ENTITY_TYPE_POST.getStatus(), comment.getId());
                commentVo.put("commentLikeStatus", commentLikeStatus);
                // 回复列表
                List<Comment> replyList = commentService.findCommentsByEntity(
                        StatusEnum.ENTITY_TYPE_COMMENT.getStatus(), comment.getId(), 0, Integer.MAX_VALUE);
                // 回复vo列表
                List<Map<String, Object>> replyVoList = new ArrayList<>();
                if (Objects.nonNull(replyList)) {
                    for (Comment reply : replyList) {
                        Map<String, Object> replyVo = new HashMap<>();
                        // 回复
                        replyVo.put("reply", reply);
                        // 作者
                        replyVo.put("user", userService.getUserById(reply.getUserId()));
                        // 回复目标
                        User target = reply.getTargetId() == 0 ? null : userService.getUserById(reply.getTargetId());
                        replyVo.put("target", target);
                        // 帖子评论回复的点赞数
                        Long replyLikeCount = likeService.findEntityLikeCount(StatusEnum.ENTITY_TYPE_POST.getStatus(), reply.getId());
                        replyVo.put("replyLikeCount", replyLikeCount);
                        // 当前用户查看帖子的评论回复点赞状态
                        Integer replyLikeStatus = likeService.findEntityLikeStatus(userId, StatusEnum.ENTITY_TYPE_POST.getStatus(), reply.getId());
                        replyVo.put("replyLikeStatus", replyLikeStatus);
                        replyVoList.add(replyVo);
                    }
                }
                commentVo.put("replys", replyVoList);
                // 回复数量
                int replyCount = commentService.findCommentCount(StatusEnum.ENTITY_TYPE_COMMENT.getStatus(), comment.getId());
                commentVo.put("replyCount", replyCount);
                commentVoList.add(commentVo);
            }
            model.addAttribute("comments", commentVoList);

        }
        return "/site/discuss-detail";
    }

    /**
     * 置顶
     * @param id（帖子id）
     * @return
     */
    @PostMapping("/top")
    @ResponseBody
    public String setTop(int id) {
        discussPostService.updateType(id, 1);
        // 触发发帖事件
        Event event = new Event()
                .setTopic(Constant.TOPIC_PUBLISH)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(StatusEnum.ENTITY_TYPE_POST.getStatus())
                .setEntityId(id);
        eventProducer.fireEvent(event);
        return WebstoreUtil.getJsonString(200);
    }

    /**
     * 加精
     * @param id（帖子id）
     * @return
     */
    @PostMapping("/wonderful")
    @ResponseBody
    public String setWonderful(int id) {
        discussPostService.updateStatus(id, 1);
        // 触发发帖事件
        Event event = new Event()
                .setTopic(Constant.TOPIC_PUBLISH)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(StatusEnum.ENTITY_TYPE_POST.getStatus())
                .setEntityId(id);
        eventProducer.fireEvent(event);
        return WebstoreUtil.getJsonString(200);
    }

    /**
     * 删除
     * @param id（帖子id）
     * @return
     */
    @PostMapping("/delete")
    @ResponseBody
    public String setDelete(int id) {
        discussPostService.updateStatus(id, 2);
        // 触发删帖事件
        Event event = new Event()
                .setTopic(Constant.TOPIC_DELETE)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(StatusEnum.ENTITY_TYPE_POST.getStatus())
                .setEntityId(id);
        eventProducer.fireEvent(event);
        return WebstoreUtil.getJsonString(200);
    }
}
